﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;
using System.Threading;
namespace SSCCMembership
{
    public static class ConnectivityManager
    {
        static ConnectivityManager()
        {
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
            T = new Timer((o) => CheckNetworkStatus(), null, 30000, 30000);
            //CheckNetworkStatus();
        }
        static Timer T;
        static void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            CheckNetworkStatus();
        }
   
        public static void CheckNetworkStatus()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Services.Login.LoginServiceClient ASC = new Services.Login.LoginServiceClient();
                ASC.IsLoggedInCompleted += new EventHandler<Services.Login.IsLoggedInCompletedEventArgs>(ASC_IsLoggedInCompleted);
                ASC.IsLoggedInAsync();
            }
            else
            {
                NoNetwork();
            }
        }

        static void ASC_IsLoggedInCompleted(object sender, Services.Login.IsLoggedInCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                NoNetwork();
            }
            else
            {
                YesNetwork();
                if (e.Result)
                {
                    LoggedIn();
                }
                else
                {
                    LoggedOut();
                }
            }
            ((Services.Login.LoginServiceClient)sender).CloseAsync();
        }


        static bool Connected = true;
        private static void NoNetwork()
        {
            if (Connected)
            {
                BusyIndicator.Show("You are not connected to the internet.", HasProgress: false);
                Connected = false;
            }
        }
        private static void YesNetwork()
        {
            if (!Connected)
            {
                Connected = true;
                BusyIndicator.Hide();
            }
        }

        static bool IsLoggedIn = false;
        private static void LoggedIn()
        {
            if (!IsLoggedIn)
            {
                IsLoggedIn = true;
            }
        }
        private static void LoggedOut()
        {
            if (IsLoggedIn)
            {
                IsLoggedIn = false;
                ((SSCCMembership.MainPage)Application.Current.RootVisual).Logout();
            }
        }
    }
}
